<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { getListApi, delListApi, getFieldEnumApi } from '@/api/customerContcat'
import { CurdData, FieldEnum } from '@/api/customerContcat/types'
import { getListApi as getCustomerListApi } from '@/api/customer'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { ElMessage } from 'element-plus'
import useSchema from './components/hooks/useSchema'
import { useTableDialogStore } from '@/store/modules/tableDialog'
import DialogChecked from './components/DialogChecked/index.vue'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { ActionButtonsTemplate } from '@/api/global/types'

const tableDialogStoreID = 'customerContactPage'
const itemTitleName = 'cusname'

const tableDialogStore = useTableDialogStore(tableDialogStoreID)

// 客户选择弹窗引用
const customerDialogRef = ref()

defineOptions({
  name: 'CustomerContactPage'
})

const { push } = useRouter()

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  params.cusid = tableDialogStore.selectedItems.map((item) => item.id).join(',')
  searchParams.value = params
  getList()
}

// 重置搜索参数
const resetSearchParams = (params: any) => {
  // 清空关联客户
  tableDialogStore.reset()
  // 重置搜索参数
  searchParams.value = {}
  // 重新获取列表
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState

    const res = await getListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delListApi(unref(ids).join(','))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

getList()

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

const { t } = useI18n()
// Begin CRUD Template Block
// ------------------------
const delData = async (row: CurdData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: CurdData) => v.id) || []

  if (ids.value.length === 0) {
    ElMessage.error(t('common.selectData'))
    return
  }
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: CurdData, type: string) => {
  push(`/customer/contactList/${type}?id=${row.id}`)
}
// 定义表格对话框的 CRUD 模式

const allSchemas = ref<AllSchemas>({
  searchSchema: [], // 确保与接口匹配
  tableColumns: [] // 确保与接口匹配
})

const fieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化
getFieldEnumApi({ field: 'all' })
  .then((res) => {
    fieldEnum.value = res.data

    const tableDialogCurdSchema = reactive<CrudSchema[]>([
      {
        field: 'selection',
        search: {
          hidden: true
        },
        form: {
          hidden: true
        },
        detail: {
          hidden: true
        },
        table: {
          type: 'selection'
        }
      },
      {
        field: 'id',
        label: t('customerContact.id'),
        search: {
          hidden: true
        },
        table: {
          headerAlign: 'center',
          align: 'center'
        }
      },
      {
        field: 'cusname',
        label: t('customer.cusname'),
        search: {
          component: 'Input'
        },
        table: {
          headerAlign: 'center',
          align: 'center'
        }
      },
      {
        field: 'phone',
        label: t('customer.phone'),
        table: {
          headerAlign: 'center',
          align: 'center'
        }
      },
      {
        field: 'email',
        label: t('customer.email'),
        search: {
          hidden: true
        },
        table: {
          headerAlign: 'center',
          align: 'center'
        }
      },
      {
        field: 'tripartite_channel_id',
        label: t('customer.tripartite_channel_id'),
        search: {
          component: 'Select',
          componentProps: {
            options: fieldEnum.value?.tripartite_channel,
            style: {
              width: '100%'
            }
          }
        },
        table: {
          headerAlign: 'center',
          align: 'center',
          slots: {
            default: (data: any) => {
              for (const key in fieldEnum.value?.tripartite_channel) {
                if (
                  fieldEnum.value?.tripartite_channel[key].value === data.row.tripartite_channel_id
                ) {
                  return fieldEnum.value?.tripartite_channel[key].label
                }
              }
            }
          }
        }
      },
      {
        field: 'tripartite_account',
        label: t('customer.tripartite_account'),
        search: {
          hidden: true
        },
        table: {
          headerAlign: 'center',
          align: 'center'
        }
      }
    ])
    const actionButtonsTemplate: ActionButtonsTemplate = {
      length: 3,
      template: (data: any) => {
        return (
          <>
            <BaseButton size="small" onClick={() => action(data.row, 'edit')}>
              {t('action.edit')}
            </BaseButton>
            <BaseButton size="small" type="success" onClick={() => action(data.row, 'detail')}>
              {t('action.detail')}
            </BaseButton>
            <BaseButton size="small" type="danger" onClick={() => delData(data.row)}>
              {t('action.del')}
            </BaseButton>
          </>
        )
      }
    }

    const { crudSchemas, handleCustomerSelect } = useSchema(
      actionButtonsTemplate,
      fieldEnum.value,
      tableDialogCurdSchema,
      undefined,
      tableDialogStoreID,
      customerDialogRef
    )
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      searchSchema: newSchemas.searchSchema || [],
      tableColumns: newSchemas.tableColumns || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })

// const { allSchemas } = useCrudSchemas(crudSchemas)
// End CRUD Template Block
// ------------------------

const AddAction = () => {
  push('/customer/contactList/add')
}

const delLoading = ref(false)

// 客户选择回调
const handleCustomerSelect = (val: any[]) => {
  if (!val || !val.length) return

  // 更新 store 中的选中项
  const selectedItems = val.map((item) => ({
    id: item.id,
    title: item.cusname
  }))
  tableDialogStore.setCheckedItems(selectedItems)
}

// 清空 store 数据
onBeforeUnmount(() => {
  tableDialogStore.reset()
})
</script>

<template>
  <ContentWrap>
    <Search
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="resetSearchParams"
    />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction" v-hasPermi="['customerContactAdd']">{{
        t('action.add')
      }}</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('action.del') }}
      </BaseButton>
    </div>

    <Table
      showAction
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />

    <!-- 客户选择弹窗 -->
    <DialogChecked ref="customerDialogRef" @expose-multiple-data="handleCustomerSelect" />
  </ContentWrap>
</template>
<style lang="less">
@import url('@/styles/global.less');
</style>
@/hooks/event/useEventBus
